package com.wnnight.wys.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author rzh6230
 * 2022/9/6 15:56
 */

@Component
public class CORSFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
//        ServletContext context = config.getServletContext();
//        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
//        jwtUtil = applicationContext.getBean(JwtUtil.class);
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        resp.setHeader("Access-Control-Max-Age", "1800");//30分钟
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, token");
        resp.setHeader("Access-Control-Expose-Headers", "jwt");
        if ("OPTIONS".equals(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, response);
    }

}
